<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="/static/layui/css/layui.css">
    <!-- 移除重复加载的Layui库 -->
    <script src="/static/jquery/jquery.js"></script>
    <script>
        console.log('Layui loaded immediately after script:', typeof layui !== 'undefined');
        console.log('jQuery loaded:', typeof $ !== 'undefined');
    </script>
</head>

<body class="layui-layout-body">
    <div class="layui-layout layui-layout-admin">

        <!-- 内容区域 -->
        <div class="layui-body" style="padding: 0; position: absolute; top: 0; bottom: 0; left: 0; right: 0;">
            <div style="padding: 15px;">
                <div class="layui-row">
                    <div class="layui-col-md12">
                        <h1>用户管理</h1>

                        <div style="margin-bottom: 20px;">
                            <button class="layui-btn" id="addUserBtn">添加用户</button>
                        </div>

                        <table class="layui-table" lay-data="{id:'userTable', height:'full-150', page:true}"
                            lay-filter="userTable">
                            <thead>
                                <tr>
                                    <th lay-data="{field:'id', width:80, sort:true}">ID</th>
                                    <th lay-data="{field:'username', width:150}">用户名</th>
                                    <th lay-data="{field:'password', width:200}">密码</th>
                                    <th lay-data="{field:'rolename', width:150}">角色</th>
                                    <th lay-data="{field:'action', width:200, toolbar:'#userActionBar'}">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for user in users %}
                                <tr>
                                    <td>{{ user.id }}</td>
                                    <td>{{ user.username }}</td>
                                    <td>{{ user.password }}</td>
                                    <td>{{ user.role.name }}</td>
                                    <td></td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑用户表单 -->
    <div id="userForm" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="userForm">
            <input type="hidden" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名"
                        autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
                        autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">角色</label>
                <div class="layui-input-block">
                    <select name="role_id" lay-verify="required">
                        <option value="">请选择角色</option>
                        {% for role in roles %}
                        <option value="{{ role.id }}">{{ role.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formSubmit">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="userActionBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

    <script src="/static/layui/layui.js"></script>
    <script>
        // 移除重复的事件绑定和错误的选择器
        // 整合到下面的layui.use回调中处理
        // 使用Layui的use方法确保DOM加载完成
          layui.use(function() {
            console.log('Layui use callback executed');
            layui.use(['table', 'form', 'jquery', 'layer'], function () {
                var table = layui.table;
                var form = layui.form;
                var $ = layui.jquery;
                var layer = layui.layer;

                    // 检查按钮元素是否存在
                console.log('添加用户按钮元素:', $('#addUserBtn'));
                console.log('按钮数量:', $('#addUserBtn').length);

                // 监听添加用户按钮点击事件
                $(document).on('click', '#addUserBtn', function() {
                    console.log('添加用户按钮被点击');
                    layer.open({
                        type: 1,
                        title: '添加用户',
                        content: $('#userForm'),
                        area: ['500px', '400px'],
                        success: function() {
                            // 清空表单
                            $('#userForm')[0].reset();
                            // 设置表单提交URL
                            $('#userForm form').attr('action', '/admin/users/add');
                            // 移除隐藏的id字段
                            $('input[name="id"]').remove();
                            // 重新渲染表单
                            form.render();
                        }
                    });
                });

                // 监听表单提交
                form.on('submit(formSubmit)', function(data) {
                    $.ajax({
                        url: data.form.action,
                        type: 'POST',
                        data: data.field,
                        dataType: 'json',
                        success: function(res) {
                            if (res.success) {
                                layer.msg('操作成功', { icon: 1 });
                                // 关闭弹窗
                                layer.closeAll();
                                // 刷新表格
                                table.reload('userTable');
                            } else {
                                layer.msg(res.msg || '操作失败', { icon: 2 });
                            }
                        }
                    });
                    return false;
                });

            // 表格操作
            table.on('tool(userTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'del') {
                    layer.confirm('确认删除该用户吗？', function (index) {
                        $.post('/admin/users/delete/' + data.id, function (res) {
                            if (res.success) {
                                obj.del();
                                layer.close(index);
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                        });
                    });
                    } else if (obj.event === 'edit') {
                        layer.open({
                            type: 1,
                            title: '编辑用户',
                            area: ['500px', '350px'],
                            content: $('#userForm'),
                            success: function () {
                                form.val('userForm', {
                                    id: data.id,
                                    username: data.username,
                                    password: data.password,
                                    role_id: data.role_id
                                });
                            }
                        });
                    }
                });

                // 表单提交
                form.on('submit(formSubmit)', function (data) {
                    var url = data.field.id ? '/admin/users/edit/' + data.field.id : '/admin/users/add';
                    $.post(url, data.field, function (res) {
                        if (res.success) {
                            layer.msg('操作成功', { icon: 1 });
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        } else {
                            layer.msg(res.msg || '操作失败', { icon: 2 });
                        }
                    });
                    return false;
                });
            });
        });
    </script>
</body>

</html>